<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { aliPay, getPaymentFlowByOrderId } from "@/api/user";
import { getOrderByNumber } from "@/api/user";

interface OrderDetail {
  orderId: number;
  orderNumber: string;
  userId: number;
  finalPrice: number;
  originalPrice: number;
  movieName: string;
  cinema: string;
  hall: string;
  time: string;
  seats: string[];
  status: string;
  createTime: string;
  serviceFee: number;
  couponAmount: number;
  couponName: string;
  moviePoster?: string;
  ticketCode?: string;
  ticketCount?: number;
}

const route = useRoute();
const router = useRouter();
const isProcessingPayment = ref(false);

const orderDetail = ref<OrderDetail>({
  orderId: 0,
  orderNumber: "",
  userId: 0,
  finalPrice: 0,
  originalPrice: 0,
  movieName: "",
  cinema: "",
  hall: "",
  time: "",
  seats: [],
  status: "",
  createTime: "",
  serviceFee: 5,
  couponAmount: 0,
  couponName: "",
});
// 初始化
onMounted(() => {
  console.log("路由参数:", route.query);

  // ✅ 如果通过支付页面跳转，带有完整 orderData
  if (route.query.orderData) {
    try {
      const data = JSON.parse(route.query.orderData as string);
      console.log("解析到的订单数据:", data);

      orderDetail.value = {
        orderId: data.orderId,
        orderNumber: data.orderNumber,
        userId: Number(localStorage.getItem("userId")),
        finalPrice: data.finalPrice || 0,
        originalPrice: data.originalPrice || 0,
        movieName: data.movieName,
        cinema: data.cinema || "星光国际影城（北京朝阳店）",
        hall: data.hall,
        time: data.time,
        seats: (data.selectedSeats || []).map(
          (s: { row: string; col: number }) => `${s.row}${s.col}`
        ),
        status: data.status || "待支付",
        createTime: new Date().toLocaleString(),
        serviceFee: data.serviceFee || 5,
        couponAmount: data.couponAmount || 0,
        couponName: data.couponName || "",
        moviePoster: data.moviePoster,
      };

      console.log("✅ 绑定的订单详情:", orderDetail.value);
    } catch (err) {
      console.error("❌ orderData 解析失败:", err);
    }
  }
  console.log(route.query.orderNumber);

  // ✅ 刷新/从订单列表跳转：使用 orderNumber 重新从后台查
  if (route.query.orderNumber) {
    fetchOrderDetail(route.query.orderNumber as string);
  } else {
    console.warn("⚠️ 既没有 orderData，也没有 orderNumber，无从获取订单数据");
  }
});

const fetchOrderDetail = async (orderNumber: string) => {
  try {
    const res = await getOrderByNumber(orderNumber);
    console.log("✅ 后端查询订单1详情:", res);
    const data = res.data.data;

    console.log("✅ 后端查询订单详情:", data);

    orderDetail.value = {
      orderId: data.orderId,
      orderNumber: data.orderNumber,
      userId: Number(localStorage.getItem("userId")),

      originalPrice: data.originalPrice,
      finalPrice: data.finalPrice,

      movieName: data.movieName,
      cinema: data.cinemaName,
      hall: data.hallNumber,
      time: data.startTime,
      seats: data.seatCoordinates ? data.seatCoordinates.split(",") : [],

      status:
        data.statues === 1
          ? "已支付"
          : data.statues === 0
          ? "待支付"
          : data.statues === 2
          ? "已退票"
          : "已完成",

      createTime: data.orderTime,

      serviceFee: data.serviceFee ?? 5,
      couponAmount: data.couponValue ?? 0,
      couponName: data.couponName ?? "",

      moviePoster: data.movieImage, // ✅直接绑定用于显示海报
      ticketCode: data.ticketCode,
      ticketCount: data.ticketCount,
    };

    console.log("✅ 最终绑定的订单详情:", orderDetail.value);
  } catch (error) {
    console.error("❌ 获取订单详情失败:", error);
  }
};

// 处理支付逻辑
const handlePayment = async () => {
  // 检查登录状态
  const token = localStorage.getItem("token");
  const userId = localStorage.getItem("userId");

  if (!token || !userId) {
    // 保存当前页面信息
    localStorage.setItem("redirectPath", route.path);
    localStorage.setItem("redirectQuery", JSON.stringify(route.query));

    alert("请先登录后再进行支付");
    router.push("/login");
    return;
  }

  if (!orderDetail.value) {
    alert("订单信息有误，请重新下单");
    return;
  }

  try {
    isProcessingPayment.value = true;

    const payData = {
      orderId: orderDetail.value.orderId,
      orderNumber: orderDetail.value.orderNumber,
      userId: orderDetail.value.userId,
      finalPrice: orderDetail.value.finalPrice,
    };

    console.log("支付参数:", payData);

    const payRes = await aliPay(payData);

    console.log("支付接口完整响应:", payRes);
    console.log("支付接口响应数据类型:", typeof payRes.data);

    // 处理支付宝返回的HTML表单
    if (typeof payRes.data === "string") {
      // 创建临时div来解析HTML
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = payRes.data;

      // 查找表单并自动提交
      const form = tempDiv.querySelector("form");
      if (form) {
        // 记录支付前的订单状态，用于支付完成后验证
        localStorage.setItem(
          "pendingOrderId",
          orderDetail.value.orderId.toString()
        );
        document.body.appendChild(tempDiv);
        form.submit();
      } else {
        // 如果找不到表单，可能是错误响应
        console.error("支付宝返回的表单不存在");
        alert("支付请求失败，无法生成支付表单");
      }
    } else {
      // 如果是对象，按照返回的逻辑处理
      if (payRes.data && (payRes.data.success || payRes.data.code === 200)) {
        const payUrl = payRes.data.data?.payUrl || payRes.data.payUrl;
        if (payUrl) {
          // 记录支付前的订单状态
          localStorage.setItem(
            "pendingOrderId",
            orderDetail.value.orderId.toString()
          );
          window.location.href = payUrl;
        } else {
          throw new Error("支付URL为空");
        }
      } else {
        const errorMsg =
          payRes.data?.message || payRes.data?.msg || "支付请求失败，请重试";
        alert(errorMsg);
      }
    }
  } catch (err) {
    console.error("支付失败", err);
    const errorMsg =
      err.response?.data?.message || err.message || "支付过程出错，请重试";
    alert(errorMsg);
  } finally {
    isProcessingPayment.value = false;
  }
};

// 查看支付流水
const goToPaymentFlow = async () => {
  console.log("请求支付流水，订单ID:", orderDetail.value.orderId); // 确保 orderId 是有效的
  try {
    const res = await getPaymentFlowByOrderId(orderDetail.value.orderId);
    console.log("支付流水接口返回:", res); // 输出接口响应

    if (res.data.code == 200) {
      const transactionId = res.data.data.transactionId;
      console.log("获取到流水ID:", transactionId, "准备跳转");

      // 确保 flowId 是有效的
      if (transactionId) {
        router.push(`/paymentFlow/${transactionId}`);
      } else {
        console.warn("未找到有效的 transactionId，无法跳转");
        alert("未找到支付流水记录");
      }
    } else {
      console.warn("未找到支付流水记录，响应数据:", res.data);
      alert("未找到支付流水记录");
    }
  } catch (error) {
    console.error("获取支付流水失败:", error); // 输出错误信息
    alert("获取支付流水失败");
  }
};

const goToHome = () => {
  console.log("跳转到首页");
  router.push("/reying");
};
const goToOrderList = () => {
  console.log("跳转到订单列表");
  router.push("/myorder");
};
</script>

<template>
  <!-- 模板内容不变 -->
  <div class="order-detail-page">
    <!-- 进度条 -->
    <div class="progress-bar">
      <div class="progress-container">
        <div class="progress-step active">1</div>
        <div class="progress-line active"></div>
        <span class="progress-text active">选座</span>
        <div class="progress-line active"></div>
        <div class="progress-step active">2</div>
        <div
          class="progress-line"
          :class="{ active: orderDetail.status === '已支付' }"
        ></div>
        <span class="progress-text active">支付</span>
        <div
          class="progress-line"
          :class="{ active: orderDetail.status === '已支付' }"
        ></div>
        <div
          class="progress-step"
          :class="{ active: orderDetail.status === '已支付' }"
        >
          3
        </div>
        <div class="progress-line"></div>
        <span
          class="progress-text"
          :class="{ active: orderDetail.status === '已支付' }"
          >完成</span
        >
      </div>
    </div>

    <!-- 订单状态 -->
    <div class="order-status-section">
      <div
        class="status-card"
        :class="{
          paid: orderDetail.status === '已支付',
          unpaid: orderDetail.status === '待支付',
          refunded: orderDetail.status === '已退票',
        }"
      >
        <div class="status-icon">
          <span v-if="orderDetail.status === '已支付'">✅</span>
          <span v-else-if="orderDetail.status === '已退票'">↩️</span>
          <span v-else>⏳</span>
        </div>
        <div class="status-info">
          <h3>
            {{
              orderDetail.status === "已支付"
                ? "支付成功"
                : orderDetail.status === "已退票"
                ? "已退票"
                : "等待支付"
            }}
          </h3>
          <p v-if="orderDetail.status === '待支付'">
            请在15分钟内完成支付，超时订单将自动取消
          </p>
          <p v-else-if="orderDetail.status === '已支付'">
            您已成功支付，请前往影院取票
          </p>
          <p v-else-if="orderDetail.status === '已退票'">
            订单已退票，退款将原路返回
          </p>
        </div>
      </div>
    </div>

    <div class="order-detail-container">
      <!-- 订单信息 -->
      <div class="order-info-section">
        <h3>订单信息</h3>

        <div class="order-header">
          <div class="order-number">
            <strong>订单号：</strong>{{ orderDetail.orderNumber }}
          </div>
          <div class="order-time">
            <strong>下单时间：</strong>{{ orderDetail.createTime }}
          </div>
        </div>

        <div class="movie-details">
          <div class="movie-poster">
            <img
              :src="orderDetail.moviePoster || ''"
              :alt="orderDetail.movieName"
              class="poster-img"
            />
          </div>

          <div class="movie-info">
            <h4>{{ orderDetail.movieName }}</h4>
            <div class="detail-item">
              <span class="label">影院：</span>
              <span class="value">{{ orderDetail.cinema }}</span>
            </div>
            <div class="detail-item">
              <span class="label">影厅：</span>
              <span class="value">{{ orderDetail.hall }}</span>
            </div>
            <div class="detail-item">
              <span class="label">场次：</span>
              <span class="value">{{ orderDetail.time }}</span>
            </div>
            <div class="detail-item" v-if="orderDetail.seats.length > 0">
              <span class="label">座位：</span>
              <span class="value seats">{{
                orderDetail.seats.join(", ")
              }}</span>
            </div>
          </div>
        </div>

        <div class="price-section">
          <div class="price-item">
            <span>票价 ({{ orderDetail.seats.length }}张)</span>
            <span>¥{{ orderDetail.originalPrice }}</span>
          </div>

          <div class="price-item">
            <span>服务费</span>
            <span>¥{{ orderDetail.serviceFee }}</span>
          </div>
          <div class="price-item" v-if="orderDetail.couponAmount > 0">
            <span>优惠券抵扣 ({{ orderDetail.couponName }})</span>
            <span class="discount">-¥{{ orderDetail.couponAmount }}</span>
          </div>

          <div class="total-price">
            <span>实付款</span>
            <span class="price">¥{{ orderDetail.finalPrice }}</span>
          </div>
        </div>
      </div>

      <!-- 支付操作 -->
      <div class="payment-section" v-if="orderDetail.status === '待支付'">
        <h3>支付方式</h3>

        <div class="payment-methods">
          <div class="payment-method active">
            <div class="method-icon">💰</div>
            <div class="method-info">
              <div class="method-name">支付宝支付</div>
              <div class="method-desc">推荐使用支付宝扫码支付</div>
            </div>
            <div class="method-check">✓</div>
          </div>
        </div>

        <div class="payment-actions">
          <button
            @click="handlePayment"
            class="pay-btn"
            :disabled="isProcessingPayment"
          >
            {{
              isProcessingPayment
                ? "支付中..."
                : `确认支付 ¥${orderDetail.finalPrice}`
            }}
          </button>
        </div>
      </div>

      <!-- 完成操作 -->
      <div class="completion-section" v-else>
        <div class="completion-actions">
          <button @click="goToHome" class="home-btn">返回首页</button>
          <button @click="goToPaymentFlow" class="flow-btn">
            查看支付流水
          </button>
          <button @click="goToOrderList" class="order-list-btn">
            查看订单
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 样式内容不变 */
.order-detail-page {
  padding: 20px;
  width: 1200px;
  margin: 0 auto;
}

/* 进度条样式 */
.progress-bar {
  margin-bottom: 30px;
}

.progress-container {
  display: flex;
  align-items: center;
  max-width: 600px;
  margin: 0 auto;
}

.progress-step {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #ddd;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.progress-step.active {
  background-color: #a2131d;
  color: white;
}

.progress-line {
  flex: 1;
  height: 2px;
  background-color: #ddd;
  margin: 0 10px;
}

.progress-line.active {
  background-color: #a2131d;
}

.progress-text {
  color: #999;
  font-size: 14px;
}

.progress-text.active {
  color: #a2131d;
  font-weight: bold;
}

/* 订单状态区域 */
.order-status-section {
  margin-bottom: 30px;
}

.status-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.status-card.paid {
  border-left: 4px solid #4caf50;
}

.status-card.unpaid {
  border-left: 4px solid #ff9800;
}
.status-card.refunded {
  border-left: 4px solid #9e9e9e;
}

.status-icon {
  font-size: 24px;
  margin-right: 15px;
}

.status-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.status-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 订单详情容器 */
.order-detail-container {
  display: flex;
  gap: 30px;
}

/* 订单信息区域 */
.order-info-section {
  flex: 1;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-info-section h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 14px;
  color: #666;
}

/* 电影详情 */
.movie-details {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.movie-poster {
  flex: 0 0 120px;
}

.poster-img {
  width: 120px;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
}

.movie-info {
  flex: 1;
}

.movie-info h4 {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #333;
}

.detail-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item .label {
  color: #666;
  width: 60px;
  display: inline-block;
}

.detail-item .value {
  color: #333;
}

.detail-item .seats {
  color: #a2131d;
  font-weight: 500;
}

/* 价格区域 */
.price-section {
  border-top: 1px dashed #eee;
  padding-top: 15px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.price-item .discount {
  color: #a2131d;
}

.total-price {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-size: 16px;
  font-weight: bold;
}

.total-price .price {
  color: #a2131d;
  font-size: 18px;
}

/* 支付区域 */
.payment-section {
  flex: 0 0 350px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.payment-section h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.payment-methods {
  margin-bottom: 30px;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 2px solid #eee;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s;
}

.payment-method.active {
  border-color: #a2131d;
  background-color: #fdf2f2;
}

.method-icon {
  font-size: 24px;
  margin-right: 15px;
}

.method-info {
  flex: 1;
}

.method-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.method-desc {
  font-size: 12px;
  color: #666;
}

.method-check {
  color: #a2131d;
  font-weight: bold;
}

.payment-actions {
  margin-top: 20px;
}

.pay-btn {
  width: 100%;
  padding: 12px;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.pay-btn:hover:not(:disabled) {
  background-color: #8a1018;
}

.pay-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 完成操作区域 */
.completion-section {
  flex: 0 0 350px;
}

.completion-actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.home-btn,
.order-list-btn,
.flow-btn {
  padding: 12px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.home-btn {
  background-color: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
}

.home-btn:hover {
  background-color: #e9ecef;
}

.flow-btn {
  background-color: white;
  color: #a2131d;
  border: 1px solid #a2131d;
}

.flow-btn:hover {
  background-color: #fdf2f2;
}

.order-list-btn {
  background-color: #a2131d;
  color: white;
}

.order-list-btn:hover {
  background-color: #8a1018;
}

@media (max-width: 768px) {
  .order-detail-page {
    width: 100%;
    padding: 10px;
  }

  .order-detail-container {
    flex-direction: column;
  }

  .order-info-section,
  .payment-section {
    min-width: 100%;
  }

  .order-header {
    flex-direction: column;
    gap: 10px;
  }

  .movie-details {
    flex-direction: column;
  }
}
</style>
